package io.bloom.web.controller;

import io.bloom.search.Searchable;
import io.bloom.web.model.LinkDO;
import io.bloom.web.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@Slf4j
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    private AtomicLong atomicLong = new AtomicLong(0);

    @RequestMapping("/search")
    public Map<String, Object> search(String keyword) throws IOException {
        List<Searchable> list = searchService.search(keyword);

        return new HashMap<String, Object>() {
            {
                put("keyword", keyword);
                put("result", list);
            }
        };
    }

    @RequestMapping("/index")
    public Map<String, Object> index(String title, String body) throws IOException {

        if (title == null || body == null) {
            return Collections.emptyMap();
        }

        LinkDO linkDO = new LinkDO();
        linkDO.setId(atomicLong.addAndGet(1));
        linkDO.setTitle(title);
        linkDO.setBody(body);

        searchService.index(linkDO);

        return new HashMap<String, Object>() {
            {
                put("message", "index successfully - " + atomicLong.get());
                put("title", title);
                put("body", body);
                put("body", body);
            }
        };
    }
}
